<?php
/* @var $var string */

/* @var $model array */

use backend\models\file\AttExtend;
use kartik\file\FileInput;
use yii\helpers\Html;
use yii\helpers\Url;
use yii\widgets\ActiveForm;

$upload_url = Url::toRoute('api-upload');
?>

<style>
    td {
        vertical-align: middle !important;
    }

    .input-group-btn .btn {
        height: 30px;
    }
</style>

<div class="org-form">
    <?php $form = ActiveForm::begin([
        "options" => [
            'id' => 'dataForm2',
        ],

    ]); ?>
    <table class="table table-condensed table-bordered">
        <tr>
            <td>推荐意见盖章扫描件:</td>
            <td>
                <div class="form-group field-attachment_id required" style="width: 80%">
                    <?php
                    echo FileInput::widget([
                        'name' => 'attachment_id',
                        'options' => ['multiple' => false],
                        'pluginOptions' => [
                            // 需要预览的文件格式
                            // 'previewFileType' => 'image',
                            'allowedFileExtensions' => ['pdf'],
                            'autoReplace' => true,
                            'showPreview' => false,
                            // 预览的文件
                            // 'initialPreview' => $p1,
                            // 需要展示的图片设置，比如图片的宽度等
                            // 'initialPreviewConfig' => $p2,
                            // 是否展示预览图
                            'initialPreviewAsData' => FALSE,
                            // 异步上传的接口地址设置
                            'uploadUrl' => $upload_url,
                            // 异步上传需要携带的其他参数，比如商品id等
                            'uploadExtraData' => [
                                'type' => 'attachment_id',
                                'id' => $model->attachment_id ? $model->attachment_id : '',
                            ],
                            'msgPlaceholder' => 'pdf文档',
                            'msgNoFilesSelected' => '请上传10M以内的pdf文件',
                            'dropZoneEnabled' => false,
                            'uploadAsync' => true,
                            // 最少上传的文件个数限制
                            'minFileCount' => 1,
                            // 最多上传的文件个数限制
                            'maxFileCount' => 1,
                            // 限制文件大小，单位KB
                            'maxFileSize' => 10 * 1024,
                            // 是否显示移除按钮，指input上面的移除按钮，非具体图片上的移除按钮
                            'showRemove' => true,
                            // 是否显示上传按钮，指input上面的上传按钮，非具体图片上的上传按钮
                            'showUpload' => true,
                            //是否显示[选择]按钮,指input上面的[选择]按钮,非具体图片上的上传按钮
                            'showBrowse' => true,
                            'showClose' => false,
                            'showCancel' => FALSE,
                            'language' => 'zh',
                            // 展示图片区域是否可点击选择多文件
                            'browseOnZoneClick' => FALSE,
                            // 如果要设置具体图片上的移除、上传和展示按钮，需要设置该选项
                            'fileActionSettings' => [
                                // 设置具体图片的查看属性为false,默认为true
                                'showZoom' => false,
                                // 设置具体图片的上传属性为true,默认为true
                                'showUpload' => FALSE,
                                // 设置具体图片的移除属性为true,默认为true
                                'showRemove' => false,
                            ],
                        ],
                        'pluginEvents' => [
                            // 上传成功后的回调方法，需要的可查看data后再做具体操作，一般不需要设置
                            "fileuploaded" => "function (event, data, id, index) {
                                uploaded_cb2(data)
                            }", 'error' => "function (){
                                alert('上传失败');
                            }"
                        ],
                    ]);
                    ?>
                    <?php
                    $att_extend = AttExtend::get_file_by_attachment_id((string)$model->attachment_id);
                    $att_extend = $att_extend ? $att_extend[0] : [];
                    if ($att_extend) {
                        $file_att_position = $att_extend ? $att_extend['att_position'] : 'javascript:;';
                        $file_file_name = $att_extend ? $att_extend['file_name'] : '';
                        $file_file_id = $att_extend ? $att_extend['uuid'] : '';
                        echo '<a target="_blank" class="file_attr_attachment_id" href="' . Url::to(['common/down-file', 'id' => $file_file_id]) . '">' . $file_file_name . '</a>';
                    }

                    $formName = $model->formName();
                    echo $model->attachment_id
                        ? '<input type="hidden" id="attachment_id"  class="file_attr_attachment_id_text fileinput" name="' . $formName . '[attachment_id]" value="' . $model->attachment_id . '">'
                        : '<input type="hidden" id="attachment_id" class="file_attr_attachment_id_text fileinput" name="' . $formName . '[attachment_id]" value="">';

                    ?>

                    <div class="help-block"></div>
                </div>
            </td>
        </tr>
    </table>
    <div class="form-group">
        <?= Html::submitButton('保存', [
            'class' => 'btn btn-primary',
            'style' => 'margin-left:480px;'
        ]) ?>
    </div>
    <?php ActiveForm::end(); ?>
</div>
<?php
$formJs = <<<JS
    $(".fileinput").each(function(index, ele){
        var id = $(ele).attr("id");
        var lable = $(ele).parents(".form-group").find(".control-label").text();
        jQuery('#dataForm2').yiiActiveForm("add", {
            "id": id,
            "container": ".field-"+id,
            "input": "#"+id,
            "validate": function (attribute, value, messages, deferred, form) {
                yii.validation.required(value, messages, {"message":"请上传推荐意见盖章扫描件。"});
            }
        });
    })

    $('#dataForm2').on("beforeSubmit",function(){
        if($(this).find(".has-error").length>0){
            return false;
        }
    });
JS;
$this->registerJs($formJs);
?>
<script>

    function uploaded_cb2(data) {
        var type = data['extra']['type'];
        console.log('data:', data);
        console.log('type:', type);
        var r_data = data['response'];
        console.log('r_data:', r_data);
        if (r_data['code'] == 1) {
            var attr = data['response']['data']['attr_extend'];
            console.log('attr:', attr);


            var a = $('.file_attr_' + type.toString());
            var i = $('.file_attr_' + type.toString() + '_text');

            a.attr('href', attr['att_position']);
            a.html(attr['file_name']);
            i.val(attr['main_att_id']);

            $(".field-attachment_id").removeClass("has-error")
            $(".field-attachment_id").find('.help-block').html('')
        } else {
            alert(r_data.msg);
        }
    }


</script>
